package cn.jx.cjm.security.support;

import cn.jx.cjm.security.service.ISysRoleService;
import cn.jx.cjm.common.base.BaseRequest;
import cn.jx.cjm.common.util.BeanUtils;
import cn.jx.cjm.security.common.constant.SecurityCacheNameConstants;
import cn.jx.cjm.security.dto.request.SysRoleRequest;
import cn.jx.cjm.security.dto.response.SysRoleResponse;
import cn.jx.cjm.security.entity.SysPermission;
import cn.jx.cjm.security.entity.SysRole;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 角色信息 业务处理层
 *
 * @author James Chen
 * @since 2019-12-16
 */

@Service
public class SysRoleSupportService {


    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private SysPermissionSupportService sysPermissionSupportService;


    public IPage<SysRoleResponse> list(BaseRequest<SysRole> request) {
        IPage<SysRole> entityIPage = sysRoleService.page(request.getPage(), request.getQueryWrapper());
        //定义返回结果
        IPage<SysRoleResponse> result = new Page<>();
        result.setTotal(entityIPage.getTotal());
        result.setCurrent(entityIPage.getCurrent());
        result.setSize(entityIPage.getSize());
        result.setPages(entityIPage.getPages());
        //转类数据
        List<SysRoleResponse> responseList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(entityIPage.getRecords())) {
            for (SysRole temp : entityIPage.getRecords()) {
                SysRoleResponse response = new SysRoleResponse();
                BeanUtils.copyPropertiesIgnoreNull(temp, response);

                Collection<SysPermission> sysPermissionList = sysPermissionSupportService.getPermissionByRole(temp.getId());
                if (!CollectionUtils.isEmpty(sysPermissionList)) {
                    Set<Integer> permissionIds = sysPermissionList.stream().map(SysPermission::getId).
                            collect(Collectors.toSet());
                    response.setPermissionIds(permissionIds);
                } else {
                    response.setPermissionIds(new ArrayList<>());
                }
                responseList.add(response);
            }
        }
        result.setRecords(responseList);
        return result;
    }

    @Cacheable(cacheNames = SecurityCacheNameConstants.ROLE_LIST, unless = "#result == null", key = "'ALL'")
    public List<SysRoleResponse> options() {
        List<SysRole> sysRoleList = sysRoleService.list(null);
        List<SysRoleResponse> result;
        if (!CollectionUtils.isEmpty(sysRoleList)) {
            result = new ArrayList<>(sysRoleList.size());
            for (SysRole temp : sysRoleList) {
                SysRoleResponse response = new SysRoleResponse();
                BeanUtils.copyPropertiesIgnoreNull(temp, response);
                result.add(response);
            }
        } else {
            result = new ArrayList<>(0);
        }
        return result;
    }


    @Cacheable(cacheNames = SecurityCacheNameConstants.ROLE_LIST, unless = "#result == null", key = "#id.toString()")
    public SysRoleResponse getOne(Integer id) {
        SysRole sysRole = sysRoleService.getById(id);
        SysRoleResponse result = new SysRoleResponse();
        BeanUtils.copyPropertiesIgnoreNull(sysRole, result);
        return result;
    }

    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    @CacheEvict(cacheNames = SecurityCacheNameConstants.ROLE_LIST, allEntries = true)
    public void save(SysRoleRequest request) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyPropertiesIgnoreNull(request, sysRole);
        sysRole.setCreateTime(LocalDateTime.now());
        this.sysRoleService.save(sysRole);
        //保存角色对应权限
        if (!CollectionUtils.isEmpty(request.getPermissionIds())) {
            sysPermissionSupportService.saveRolePermission(sysRole.getId(), request.getPermissionIds());
        }
    }

    /**
     * 角色权限更新
     * 更新角色对应权限后更新redis缓存信息
     *
     * @param request 角色信息
     */
    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    @CacheEvict(cacheNames = {SecurityCacheNameConstants.ROLE_PATH_LIST, SecurityCacheNameConstants.ROLE_LIST}, key = "#request.getId().toString()")
    public void update(SysRoleRequest request) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyPropertiesIgnoreNull(request, sysRole);
        sysRoleService.updateById(sysRole);
        //保存角色对应权限
        if (!CollectionUtils.isEmpty(request.getPermissionIds())) {
            sysPermissionSupportService.saveRolePermission(sysRole.getId(), request.getPermissionIds());
        }
    }


    @Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
    @CacheEvict(cacheNames = {SecurityCacheNameConstants.ROLE_PATH_LIST, SecurityCacheNameConstants.ROLE_LIST}, allEntries = true)
    public void remove(Integer id) {
        sysRoleService.removeById(id);
        sysPermissionSupportService.deleteRolePermissionByRole(id);
    }
}

